const app = getApp();
import { get } from '../../../utils/request';
import auth from '../../../utils/auth';

Page({
  data: {
    orderList: [],
    loading: true,
    tabs: [
      { value: 'available', label: '可接取订单' },
      { value: 'paid', label: '待服务' },
      { value: 'in_progress', label: '进行中' },
      { value: 'completed', label: '已完成' },
      { value: 'canceled', label: '已取消' },
      { value: 'refunded', label: '已退款' }
    ],
    activeTab: 'available',
    page: 1,
    size: 10,
    hasMore: true,
    selectedOrder: null,
    showConfirmModal: false
  },

  onLoad() {
    this.checkPermission();
    this.loadProviderOrders(this.data.activeTab);
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      orderList: []
    });
    this.loadProviderOrders(this.data.activeTab).then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreOrders();
    }
  },

  // 检查权限
  checkPermission() {
    // 只允许服务人员访问
    if (!auth.isProvider()) {
      wx.showToast({
        title: '您不是服务人员，无法访问此页面',
        icon: 'none'
      });

      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 加载服务人员订单
  loadProviderOrders(status = 'available') {
    this.setData({ loading: true });

    // 如果是可接取订单，使用getAvailableOrdersForProvider接口
    if (status === 'available') {
      return this.loadAvailableOrders();
    }

    // 否则使用listMyOrdersVOByPage接口
    const requestData = {
      current: this.data.page,
      pageSize: this.data.size,
      status: status,
      sortField: 'createTime',
      sortOrder: 'desc'
    };

    // 调用我的订单列表接口
    return wx.request({
      url: app.globalData.baseUrl + '/api/orders/provider/list/page/vo',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      data: requestData,
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0 && res.data.data) {
          const newOrders = res.data.data.records || [];

          // 确保时间字段存在且格式正确
          const processedOrders = newOrders.map(order => {
            // 统一时间字段处理
            const createTime = order.createTime
              ? new Date(order.createTime).getTime()
              : Date.now();

            const appointmentTime = order.appointmentTime
              ? new Date(order.appointmentTime).getTime()
              : Date.now() + 24 * 60 * 60 * 1000;

            return {
              ...order,
              createTime,
              appointmentTime
            };
          });

          this.setData({
            orderList: this.data.page === 1 ? processedOrders : [...this.data.orderList, ...processedOrders],
            hasMore: newOrders.length >= this.data.size,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '获取订单失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('获取订单失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 加载可接取订单
  loadAvailableOrders() {
    return get('/api/orders/available', {
      current: this.data.page,
      size: this.data.size,
      status: 'paid'
    })
      .then(res => {
        if (res.code === 0 && res.data) {
          const newOrders = res.data.records || [];

          // 确保时间字段存在且格式正确
          const processedOrders = newOrders.map(order => {
            // 统一时间字段处理
            const createTime = order.createTime
              ? new Date(order.createTime).getTime()
              : Date.now();

            const appointmentTime = order.appointmentTime
              ? new Date(order.appointmentTime).getTime()
              : Date.now() + 24 * 60 * 60 * 1000;

            return {
              ...order,
              createTime,
              appointmentTime
            };
          });

          this.setData({
            orderList: this.data.page === 1 ? processedOrders : [...this.data.orderList, ...processedOrders],
            hasMore: newOrders.length >= this.data.size,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.message || '获取订单失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      })
      .catch(err => {
        console.error('获取可接取订单失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },

  // 加载更多订单
  loadMoreOrders() {
    this.setData({
      page: this.data.page + 1
    });
    this.loadProviderOrders(this.data.activeTab);
  },

  // 返回主页
  goBack() {
    wx.switchTab({
      url: '/pages/index/index'
    });
  },

  // 切换标签
  handleTabChange(e) {
    const value = e.detail.value;

    this.setData({
      activeTab: value,
      page: 1,
      orderList: [],
      hasMore: true
    });

    this.loadProviderOrders(value);
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    const status = this.data.activeTab;

    // 如果是可接取订单，显示接单确认弹窗
    if (status === 'available') {
      const order = this.data.orderList.find(item => item.id === orderId);
      if (order) {
        // 确保选中订单的时间字段存在且格式正确
        const createTime = order.createTime || order.createAt || order.createDate || Date.now();
        const appointmentTime = order.appointmentTime || order.appointAt || order.appointDate || (Date.now() + 24 * 60 * 60 * 1000);

        const processedOrder = {
          ...order,
          createTime: createTime,
          appointmentTime: appointmentTime
        };

        this.setData({
          selectedOrder: processedOrder,
          showConfirmModal: true
        });
      }
    } else {
      // 否则跳转到订单详情页
      wx.navigateTo({
        url: `/pages/order/detail/detail?id=${orderId}&role=provider`
      });
    }
  },

  // 关闭确认弹窗
  closeConfirmModal() {
    this.setData({
      showConfirmModal: false
    });
  },

  // 接受订单
  acceptOrder() {
    if (!this.data.selectedOrder) {
      return;
    }

    const orderId = this.data.selectedOrder.id;

    // 调用接单接口
    wx.request({
      url: app.globalData.baseUrl + `/api/orders/accept/${orderId}`,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 0) {
          wx.showToast({
            title: '接单成功',
            icon: 'success'
          });

          // 关闭弹窗
          this.setData({
            showConfirmModal: false
          });

          // 刷新订单列表
          setTimeout(() => {
            this.setData({
              page: 1,
              orderList: []
            });
            this.loadProviderOrders(this.data.activeTab);
          }, 1000);
        } else {
          wx.showToast({
            title: res.data.message || '接单失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('接单失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '无';

    try {
      const date = new Date(Number(timestamp));

      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
      console.error('时间格式化失败:', error);
      return '时间格式错误';
    }
  },

  // 格式化订单状态
  formatStatus(status) {
    const statusMap = {
      'available': '可接取',
      'pending': '待支付',
      'paid': '待服务',
      'in_progress': '进行中',
      'completed': '已完成',
      'refunded': '已退款',
      'canceled': '已取消'
    };

    return statusMap[status] || status;
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      'available': '#1890ff',
      'pending': '#faad14',
      'paid': '#ff9800',
      'in_progress': '#0052D9',
      'completed': '#52c41a',
      'refunded': '#722ed1',
      'canceled': '#999999'
    };

    return colorMap[status] || '#333333';
  }
})